<template>
  <FIModel v-model="visible" title="岗位选择" @close="closeClick" @confirm="saveFunc">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :showCollapse="false"
      :table-column="columns"
      :wrapperSpan="8"
      @submit="searchFn"
    >
      <el-col :span="8">
        <FIFormItem prop="formEname" label="岗位编码">
          <FIInput v-model="state.query.postEname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="postCname" label="岗位名称">
          <FIInput v-model="state.query.postCname" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="岗位列表"
      :id="`result_${tableId}`"
      :data="dataList"
      primaryKey="formId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :showSaveModel="false"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :settingConfig="settingConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
    </FITable>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIForm from '@/components/FIForm.vue'
import FIModel from '@/components/FIModel.vue'
import { apiAuthMaintinsert, apiPostquery } from '@/api/user'
import { useMessage } from '@/hooks/message'
import { initSearchData } from '@/utils/common'
import type { PageConfig, Column } from '@/types/components'

const emits = defineEmits(['close', 'update:postShow', 'post-close'])
const props = defineProps({
  // 圆角大小
  postShow: {
    type: Boolean,
    default: false,
  },
  treeVal: {
    type: Array,
    default: () => [],
  },
  activeName: {
    type: String,
    default: '1',
  },
})
const register = reactive({
  userName: '',
  password: '',
  loginName: '',
  mobile: '',
  gender: '',
  email: '',
  businessPhone: '',
  jobNo: '',
  deptId: '',
})
const dataList = ref([])
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}

const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}

const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'pageMaint'
const state = reactive({
  query: {
    postCname: '',
    postEname: '',
    current: 1,
    size: 10,
  },
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '岗位编码',
    prop: 'postEname',
    align: 'center',
    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '岗位名称',
    prop: 'postCname',
    align: 'center',
    queryName: '',
    editable: false,
    sortable: true,
    filterable: false,
    readonly: true,
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.postShow
  },
  set(val) {
    emits('update:postShow', val)
  },
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const addRowSave = (data) => {
  handleSave(data, 'add')
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  // apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       // saveSuccessful.value = true
  //       tableRef.value.clearSelection()
  //       searchFn()
  //     } else {
  //       ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //   })
}
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    deptId: orgId || '',
    ...state.query,
  }
  apiPostquery(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        dataList.value = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const closeClick = () => {
  checkedRows.value = []
  emits('update:postShow', false, 'query')
}
const selectData = (val, name) => {
  // orgSelect.label = name
  register.deptId = val.value
}
const saveFunc = () => {
  console.log(props.treeVal, '树的数据')
  console.log(checkedRows.value, '岗位的数据')
  if (!checkedRows.value.length) {
    useMessage().warning('请选一条数据')
    return
  }
  let arr = []
  props.treeVal.forEach((item1) => {
    checkedRows.value.forEach((item2) => {
      if(item1.payload.resourceId){
        arr.push({
          resourceType: item1.payload.resourceType,
          resourceId: item1.payload.resourceId,
          subjectId: item2.postId,
          subjectType: 'POST',
        })
      }
      
    })
  })

  console.log(arr, '组装后的数据')
  apiAuthMaintinsert(arr)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)
        emits('update:postShow', false)
        emits('post-close')
      }
    })
    .catch((error: any) => {})
}

onMounted(() => {
  searchFn()
})
</script>
<style lang="less" scoped></style>
